package com.example.musicwebcon.service;

import ch.qos.logback.core.util.StringUtil;
import com.example.musicwebcon.model.dto.songListDTO;
import com.example.musicwebcon.model.songList;
import com.example.musicwebcon.repository.songListRepository;
import com.example.musicwebcon.service.serviceInterface.IsongListService;
import org.springframework.beans.BeanUtils;
import com.example.musicwebcon.util.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@Service
public class songListService implements IsongListService {
    @Autowired
    songListRepository songListRepository;

    @Override
    public songList add(songListDTO songlist) {
        String id = IdGenerator.generateSongListId();
        if(songlist.getSonglistId() == null || songlist.getSonglistId().isEmpty()){
            songlist.setSonglistId(id);
        }
        if(songlist.getSongListName() == null || songlist.getSongListName().isEmpty()){
            songlist.setSongListName("新建歌单" + id);
        }
        if (songlist.getCoverUrl() == null || songlist.getCoverUrl().isEmpty()){
            songlist.setCoverUrl("\\img\\songlistdefalt.png");
        }
        if (songlist.getDescription() == null || songlist.getDescription().isEmpty()){
            songlist.setDescription("精心完善您的歌单信息，让你的歌单更具有吸引力");
        }
        songList songList = new songList();
        BeanUtils.copyProperties(songlist,songList);
        return songListRepository.save(songList);
    }

    @Override
    public songList getsonglistId(String songlistId) {
        return songListRepository.findById(songlistId).orElseThrow(()->{
            throw new IllegalArgumentException("歌单不存在，参数异常！");
        });
    }

    @Override
    public Iterable<songList> getAllByUserId(String userId) {
        return songListRepository.findAllByUserId(userId);
    }

    @Override
    public songList edit(String id, String songListName, String description, MultipartFile file) {
        songList existingSongList = songListRepository.findById(id).orElseThrow(() -> {
            throw new IllegalArgumentException("歌单不存在，参数异常！");
        });

        if (songListName != null) existingSongList.setSongListName(songListName);
        if (description != null) existingSongList.setDescription(description);

        if (file != null) {
            try {
                String coverUrl = saveCoverImage(file);
                existingSongList.setCoverUrl(coverUrl);
            } catch (IOException e) {
                throw new RuntimeException("封面图片上传失败", e);
            }
        }

        return songListRepository.save(existingSongList);
    }

    private String saveCoverImage(MultipartFile file) throws IOException {
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        Path targetLocation = Paths.get("uploads/songlists/"+fileName);
        Files.createDirectories(targetLocation.getParent());
        file.transferTo(targetLocation);
        return "http://localhost:8088/uploads/songlists/"+fileName;
    }

    @Override
    public void deleteBysonglistId(String songlistId) {
        songListRepository.deleteById(songlistId);
    }
}
